package org.rcy.framework.thrift.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.UUID;

public class RpcLog {
	
	private static Logger logger = LoggerFactory.getLogger(RpcLog.class);
	
	public static final String FIELD_NAME = "rpcLog";
	private static final String TRACR_ID = "traceId";
	public static final String RPC_PREFIX = "RPC";
	private String logId;

	public static String checkLogId() {
		return MDC.get(RpcLog.TRACR_ID);
	}
	
	public static RpcLog initTrace() {
		try {
			String logId = MDC.get(RpcLog.TRACR_ID);
			if(isBlank(logId)) {
				logId = RpcLog.initLogId();
				MDC.put(RpcLog.TRACR_ID, logId);
			}
			RpcLog rpcLog = new RpcLog(logId);

			return rpcLog;
		} catch (Exception e) {
			logger.error("RpcLog initTrace error {}",e.getMessage(),e);
			return new RpcLog(RpcLog.initLogId());
		}
	}
	
	public static void recoverTrace(RpcLog rpcLog) {
		try {
			String tempLogId = rpcLog.getLogId();
			if(isNotBlank(tempLogId)) {
				MDC.put(RpcLog.TRACR_ID, tempLogId);
			}
		} catch (Exception e) {
			logger.error("RpcLog recoverTrace error {}",e.getMessage(),e);
		}
		
	}
	
	public static void removeTrace() {
		try {
			MDC.remove(RpcLog.TRACR_ID);
		} catch (Exception e) {
			logger.error("RpcLog removeTrace error {}",e.getMessage(),e);
		}
	}
	
	private static boolean isNotBlank(final CharSequence cs) {
		return !isBlank(cs);
	}
	
	private static boolean isBlank(final CharSequence cs) {
		int strLen;
		if (cs == null || (strLen = cs.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if (!Character.isWhitespace(cs.charAt(i))) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 自动初始化logId
	 * @return
	 */
	private static String initLogId() {
		return RPC_PREFIX + UUID.randomUUID().toString().replace("-", "").substring(15);
	}
	
	
	public RpcLog() {
		super();
	}

	public RpcLog(String logId) {
		super();
		this.logId = logId;
	}

	public String getLogId() {
		return logId;
	}

	public void setLogId(String logId) {
		this.logId = logId;
	}

}